package com.jianshuge.app.ui;

import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;
import com.jianshuge.app.bean.DoubanBook;
import com.jianshuge.app.common.StringUtils;
import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.widget.LoadingDialog;
import com.jianshuge.app.bean.MyResult;
import com.jianshuge.zxing.activity.CaptureActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AddBookResult extends BaseActivity{
	
	private ImageButton mClose;
	private EditText mEditer;
	private Button mPublish;
	private Button mFavorite;
	private LoadingDialog loading;
	
	private ProgressDialog mMyProgress;
	
	private LinearLayout book_frame;
	
	private Handler mHandler;
	private Handler mdoubanHandler;
	
	public ImageView book_image;  
	private TextView book_title;
	private TextView book_author;
	private TextView book_rating;
	private TextView book_pubdate;
	private TextView book_publisher;
	private TextView book_isbn;
	
	private String douban_subject_id = null;
	private int cur_booklist_id;
	private int cur_book_id = -1;
	private boolean is_new = true;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_book_result);
		
		this.initView();
	}
	
	//初始化视图控件
    private void initView()
    {    	
    	
		douban_subject_id = getIntent().getStringExtra("subject_id");
		cur_booklist_id = getIntent().getIntExtra("booklist_id", 0);
		cur_book_id = getIntent().getIntExtra("book_id", 0);
		
    	mClose = (ImageButton)findViewById(R.id.addbook_close_button);
    	mEditer = (EditText)findViewById(R.id.addbook_content);
    	mPublish = (Button)findViewById(R.id.addbook_publish);
    	mFavorite = (Button)findViewById(R.id.addbook_favorite);
    	
		if( cur_book_id > 0) {
			mEditer.setText(getIntent().getStringExtra("recomment"));
			mPublish.setText("更新推荐语");
			is_new = false;
		}

    	mClose.setOnClickListener(UIHelper.finish(this));
    	mPublish.setOnClickListener(publishClickListener);
    	mFavorite.setOnClickListener(favoriteClickListener);
    	
		book_frame = (LinearLayout)findViewById(R.id.add_douban_book_frame);	
		book_frame.setVisibility(View.GONE);
		
		book_image = (ImageView)findViewById(R.id.douban_book_image);
		book_title = (TextView)findViewById(R.id.douban_book_title);
		book_author = (TextView)findViewById(R.id.douban_book_author);
		book_publisher = (TextView)findViewById(R.id.douban_book_publisher);
		book_pubdate = (TextView)findViewById(R.id.douban_book_pubdate);
		book_isbn = (TextView)findViewById(R.id.douban_book_isbn);
		book_rating = (TextView)findViewById(R.id.douban_book_rating);
		
		mdoubanHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				if (msg.what == 1) {
					MyResult res = (MyResult) msg.obj;
					if (res.OK()) {
						cur_book_id = Integer.parseInt(res.getExtraCode());
					//	UIHelper.ToastMessage(AddBookResult.this, res.getErrorMessage());
					}
				} else {					
					((AppException) msg.obj).makeToast(AddBookResult.this);
				}
			}
		};
		
		
		mHandler = new Handler() {
			
			public void handleMessage(Message msg) {
				
				if (loading != null)
					loading.dismiss();
				
				if (msg.what == 1 && msg.obj != null) {
					DoubanBook doubanbook = (DoubanBook) msg.obj;
					
					String book_image_url = doubanbook.getImageUrl();
					//String small_img_url = book_image_url.replace("mpic", "spic");
					if(book_image_url.endsWith("portrait.gif") || StringUtils.isEmpty(book_image_url)){
						book_image.setImageResource(R.drawable.default_book_pic);
					}else{
					//	bmpManager.loadBitmap(book_image_url, book_image);
						UIHelper.showUserFace(book_image, book_image_url);
					}

					book_title.setText("书名： " +  doubanbook.getTitle() );
					book_author.setText("作者： " + doubanbook.getAuthor());
					book_publisher.setText("出版社： " + doubanbook.getPublisher());
					book_pubdate.setText("出版日期：" + doubanbook.getPubdate());
					book_isbn.setText("ISBN： " + doubanbook.getIsbn());
					book_rating.setText("豆瓣评分： " + doubanbook.getRating());
					
					book_frame.setVisibility(View.VISIBLE);
					douban_subject_id = doubanbook.getSubjectId();
					
					saveDoubanBookThread(douban_subject_id, mdoubanHandler, true);
					
				} else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(AddBookResult.this);
				}

			}
		};
		
		this.loadDoubanBookThread(douban_subject_id, mHandler, true);
    }
    
	private void loadDoubanBookThread(final String subject_id, final Handler handler, final boolean isRefresh){ 
		
		loading = new LoadingDialog(this);
		loading.setLoadText("正在加载···");
		loading.show();

		new Thread(){
			public void run() {
				
				Message msg = new Message();				
				try {
					
					DoubanBook doubanbook = ((AppContext)getApplication()).getDoubanBookBySubject(subject_id, isRefresh);
					msg.what = 1;
					msg.obj = doubanbook;
	            
				} catch (AppException e) {
					
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            
				}
				
                handler.sendMessage(msg);
			}
			
		}.start();
	}
	
	private void  saveDoubanBookThread(final String subject_id, final Handler handler, final boolean isRefresh){  

		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					
					MyResult res = ((AppContext)getApplication()).saveDoubanBook(subject_id, isRefresh);
					msg.what = 1;
					msg.obj = res;
				} catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
				}	
				handler.sendMessage(msg);
			}
			
		}.start();
		
	}

    private View.OnClickListener publishClickListener = new View.OnClickListener() {		
		public void onClick(View v) {
			final String content = mEditer.getText().toString();
			
			if(StringUtils.isEmpty(content)) {
				UIHelper.ToastMessage(v.getContext(), "推荐理由不能为空");
				return;
			}
			
			mMyProgress = ProgressDialog.show(v.getContext(), null, "发布中···",true,true); 
			
			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mMyProgress!=null)
						mMyProgress.dismiss();
					
					if (msg.what == 1) {
						MyResult res = (MyResult) msg.obj;
						UIHelper.ToastMessage(AddBookResult.this, res.getErrorMessage());
						if (res.OK()) {
							Intent intent = new Intent();
							intent.putExtra("message", res.getErrorMessage());
							setResult(RESULT_OK, intent);
							finish();
						}
					} else {					
						((AppException) msg.obj).makeToast(AddBookResult.this);
					}
				}
			};
			
			new Thread() {
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {
						
						AppContext ac = (AppContext)getApplication();
						final int uid = ac.getLoginUid();
						
						if( is_new == true )
							res = ac.addBookResult(uid, cur_booklist_id, cur_book_id, content);
						else
							res = ac.updateRecomment(uid, cur_booklist_id, cur_book_id, content);
						
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			}.start();
			
		}
	};
	
	private View.OnClickListener favoriteClickListener = new View.OnClickListener(){
		
		public void onClick(View v) {
			
			if ( douban_subject_id == null ) {
				return;
			}
			
			mMyProgress = ProgressDialog.show(v.getContext(), null, "收藏中···",true,true); 
		
			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mMyProgress!=null)
						mMyProgress.dismiss();
					
					if (msg.what == 1) {
						MyResult res = (MyResult) msg.obj;
						if (res.OK()) {
							UIHelper.ToastMessage(AddBookResult.this, res.getErrorMessage());
						}
					
					} else {					
						((AppException) msg.obj).makeToast(AddBookResult.this);
					}
				}
			};
			
			new Thread() {
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {
						
						AppContext ac = (AppContext)getApplication();
						final int uid = ac.getLoginUid();
						//res = ac.scanFavorite(uid, douban_subject_id);
						if( douban_subject_id != null)
							res = ac.scanFavorite(uid, douban_subject_id);
							
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			}.start();
		}
	};
}

